/* 用户注册 */

const { MongoClient, ServerApiVersion } = require('mongodb')
let dayjs = require('dayjs')

// 数据库地址
const uri = 'mongodb://localhost:27017/libraryDB'

// 连接数据库
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  },
})

// 用户注册
const userRegistration = async (data) => {
  try {
    await client.connect()
    // 获取数据库对象
    const db = client.db('libraryDB')
    // 获取student_info表
    const studentInfoDb = db.collection('users')
    // 空值校验
    if (!data.username)
      return {
        msg: '用户名不能为空',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        code: 10004,
        success: false,
      }
    if (!data.password)
      return {
        msg: '密码不能为空',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        code: 10004,
        success: false,
      }
    if (!data.name)
      return {
        msg: '姓名不能为空',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        code: 10004,
        success: false,
      }
    if (!data.contactNumber)
      return {
        msg: '手机号不能为空',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        code: 10004,
        success: false,
      }
    if (!data.studentId)
      return {
        msg: '学号不能为空',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        code: 10004,
        success: false,
      }
    // 查询手机号，账号是否被注册
    const query = {
      $or: [
        {
          contactNumber: data.contactNumber,
          studentId: data.studentId,
        },
      ],
    }
    const res = await studentInfoDb.findOne(query)
    if (!res) {
      await studentInfoDb.insertOne({
        ...data,
        created: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        updated: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        role: 'student',
      })
      return {
        msg: '注册成功',
        code: 10003,
        success: true,
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }
    } else {
      return {
        msg: '用户手机号或学号已存在',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
        code: 10004,
        success: false,
      }
    }
  } catch (error) {
  } finally {
    client.close()
  }
}

// 返回用户列表
const userDataList = async (data) => {
  try {
    await client.connect()
  } catch (error) {
  } finally {
    await client.connect()
    // 获取数据库对象
    const db = client.db('libraryDB')
    // 获取student_info表
    const studentInfoDb = db.collection('users')
    const res = await studentInfoDb.find()
    const list = []
    await res.forEach((element) => {
      list.push(element)
    })
    return {
      msg: '查询成功',
      time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      msgCode: 10000,
      data: {
        total: list.length,
        list,
        success: true,
      },
    }
  }
}
module.exports = { userRegistration, userDataList }
